<?php
declare(strict_types=1);
namespace app\admin\widget;
use aphp\core\Widget;
// 栏目选择
class TopicDir extends Widget
{
    protected string $tag = 'topic';
    protected int $expire = 0;

    public function set($id = '', array $options = []): array
    {
        $type = $options['type'] ?? 0;
        $map = [];
        $map['status'] = 1;
        if ($type > 0) {
            $map['type'] = $type;
        }
        $list = db('topic')->field('id,pid,title,level')->where($map)->order('sort ASC,id ASC')->select();
        $level = $options['level'] ?? 0; // 初始层级
        $pid = $level == 0 ? 0 : 1; // 初始父级id
        $list =  $this->_sort($list, $pid, $level);
        return array_column($list, 'title', 'id');
    }

    protected function _sort(array $list, int $pid = 0, $level = 0): array
    {
        $data = [];
        foreach($list as $vo){
            if($vo['pid'] == $pid){
                if ($vo['level'] > $level) {
                    $vo['title'] = str_repeat('&nbsp;&nbsp;&nbsp;', $vo['level']).'├─'.$vo['title'];
                }
                $data[] = $vo;
                $sub = $this->_sort($list, $vo['id'], $level);
                $data = array_merge($data, $sub);
            }
        }
        return $data;
    }
}